﻿using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;

namespace IpServer.Controllers
{
    [Route("[controller]/[action]")]
    [ApiController]
    public class IpServiceController : ControllerBase
    {
        private static readonly Dictionary<string, string> _ipDic = new Dictionary<string, string>();
        private static readonly object _ipDicLock = new object();
        private readonly ILogger<IpServiceController> _logger;

        public IpServiceController(ILogger<IpServiceController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public async Task<string> GetIp(string name)
        {
            return await Task.Run(() => {
                this.HttpContext.Response.Headers["Access-Control-Allow-Origin"] = "*";
                lock (_ipDicLock)
                {
                    if (_ipDic.ContainsKey(name))
                        return _ipDic[name];
                    else
                        return "0.0.0.0";
                }
            });
        }
        [HttpGet]
        public async void SetIp(string name,string pwd)
        {
            if (pwd != "@zmg123")
                return;
            var feature = HttpContext.Features.Get<IHttpConnectionFeature>();
            var clientIPAddr = feature?.RemoteIpAddress?.MapToIPv4().ToString();
            var serverIPAddr= feature?.LocalIpAddress?.MapToIPv4().ToString();
            if (clientIPAddr == serverIPAddr)
                return;
            await Task.Run(() => {
                lock (_ipDicLock)
                {
                    _ipDic[name] = clientIPAddr;
                }
            });
        }
    }
}
